﻿// -----------------------------------------------------------------------
// <copyright file="StringRangeValidationRule.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Globalization;
using System.Windows.Controls;
using Caliburn.Micro;
using SS.WPF.Framework.Localization;

namespace SS.WPF.Framework.ValidationRule
{
    using System.Collections.Generic;

    /// <summary>
    /// String range validation rule.
    /// </summary>
    public class StringRangeValidationRule : System.Windows.Controls.ValidationRule
    { 
        /// <summary>
        /// Minimum length.
        /// </summary>
        private int _minimumLength = -1;

        /// <summary>
        /// Maximum length.
        /// </summary>
        private int _maximumLength = -1;

        /// <summary>
        /// Gets or sets MinimumLength.
        /// </summary>
        public int MinimumLength
        {
            get { return _minimumLength; }

            set { _minimumLength = value; }
        }

        /// <summary>
        /// Gets or sets MaximumLength.
        /// </summary>
        public int MaximumLength
        {
            get { return _maximumLength; }

            set { _maximumLength = value; }
        }

        /// <summary>
        /// Validate.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="cultureInfo">
        /// The culture info.
        /// </param>
        /// <returns>
        /// ValidationResult
        /// </returns>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var result = new ValidationResult(true, null);
            var inputString = (value ?? string.Empty).ToString();
            if (inputString.Length < this.MinimumLength ||
                (this.MaximumLength > 0 && inputString.Length > this.MaximumLength))
            {
                var list = new List<string>();

                if (this.MinimumLength != -1)
                {
                    list.Add(string.Format((string) IoC.Get<TranslationManager>().Translate("Minlength"),
                                           MinimumLength).Trim(new[] {'\n', ' ', '\t'}));
                }

                if (this.MaximumLength != -1)
                {
                    list.Add(string.Format((string) IoC.Get<TranslationManager>().Translate("MaxLength"),
                                           MaximumLength).Trim(new[] {'\n', ' ', '\t'}));
                }

                var msg = string.Join("\t", list.ToArray());
                result = new ValidationResult(false, msg);
            }

            return result;
        }
    }
}
